package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.common.result.Result;
import com.vehiclemanagement.entity.FuelRefill;
import com.vehiclemanagement.service.FuelRefillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 燃油加注记录控制器
 */
@RestController
@RequestMapping("/fuel-refill")
@Slf4j
public class FuelRefillController {

    @Autowired
    private FuelRefillService fuelRefillService;

    /**
     * 分页查询加油记录
     */
    @GetMapping("/list")
    public Result<IPage<FuelRefill>> list(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "searchTerm", required = false) String searchTerm,
            @RequestParam(value = "vehicleId", required = false) Long vehicleId,
            @RequestParam(value = "driverId", required = false) Long driverId,
            @RequestParam(value = "fuelCardId", required = false) Long fuelCardId,
            @RequestParam(value = "fuelType", required = false) Integer fuelType,
            @RequestParam(value = "startTime", required = false) 
                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(value = "endTime", required = false) 
                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        log.info("分页查询加油记录: current={}, size={}, searchTerm={}, vehicleId={}, driverId={}, fuelCardId={}, fuelType={}, startTime={}, endTime={}",
                current, size, searchTerm, vehicleId, driverId, fuelCardId, fuelType, startTime, endTime);

        try {
            IPage<FuelRefill> page = fuelRefillService.pageRefills(current, size, searchTerm, vehicleId, 
                    driverId, fuelCardId, fuelType, startTime, endTime);
            return Result.success(page);
        } catch (Exception e) {
            log.error("分页查询加油记录失败", e);
            return Result.error("获取加油记录列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取加油记录详情
     */
    @GetMapping("/{id}")
    public Result<FuelRefill> getById(@PathVariable Long id) {
        log.info("获取加油记录详情: id={}", id);
        
        try {
            FuelRefill refill = fuelRefillService.getRefillById(id);
            if (refill == null) {
                return Result.error("找不到指定的加油记录");
            }
            return Result.success(refill);
        } catch (Exception e) {
            log.error("获取加油记录详情失败", e);
            return Result.error("获取加油记录详情失败：" + e.getMessage());
        }
    }

    /**
     * 添加加油记录
     */
    @PostMapping
    public Result<Boolean> add(@RequestBody FuelRefill refill) {
        log.info("添加加油记录: {}", refill);
        
        // 校验必填字段
        if (refill.getVehicleId() == null) {
            return Result.validateFailed("车辆ID不能为空");
        }
        if (refill.getDriverId() == null) {
            return Result.validateFailed("司机ID不能为空");
        }
        if (refill.getFuelCardId() == null) {
            return Result.validateFailed("燃油卡ID不能为空");
        }
        if (refill.getRefillTime() == null) {
            return Result.validateFailed("加油时间不能为空");
        }
        if (refill.getFuelType() == null) {
            return Result.validateFailed("燃油类型不能为空");
        }
        if (refill.getFuelAmount() == null) {
            return Result.validateFailed("加油量不能为空");
        }
        if (refill.getUnitPrice() == null) {
            return Result.validateFailed("单价不能为空");
        }
        if (refill.getTotalPrice() == null) {
            return Result.validateFailed("总价不能为空");
        }
        if (refill.getCurrentMileage() == null) {
            return Result.validateFailed("当前里程不能为空");
        }
        
        try {
            boolean success = fuelRefillService.addRefill(refill);
            return success ? Result.success("添加加油记录成功", true) : Result.error("添加加油记录失败");
        } catch (Exception e) {
            log.error("添加加油记录失败", e);
            return Result.error("添加加油记录失败：" + e.getMessage());
        }
    }

    /**
     * 更新加油记录
     */
    @PutMapping
    public Result<Boolean> update(@RequestBody FuelRefill refill) {
        log.info("更新加油记录: {}", refill);
        
        if (refill.getId() == null) {
            return Result.validateFailed("加油记录ID不能为空");
        }
        
        try {
            boolean success = fuelRefillService.updateRefill(refill);
            return success ? Result.success("更新加油记录成功", true) : Result.error("更新加油记录失败");
        } catch (Exception e) {
            log.error("更新加油记录失败", e);
            return Result.error("更新加油记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除加油记录
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        log.info("删除加油记录: id={}", id);
        
        try {
            boolean success = fuelRefillService.deleteRefill(id);
            return success ? Result.success("删除加油记录成功", true) : Result.error("删除加油记录失败");
        } catch (Exception e) {
            log.error("删除加油记录失败", e);
            return Result.error("删除加油记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取车辆加油总量
     */
    @GetMapping("/amount/{vehicleId}")
    public Result<BigDecimal> getFuelAmount(@PathVariable Long vehicleId) {
        log.info("获取车辆加油总量: vehicleId={}", vehicleId);
        
        try {
            BigDecimal amount = fuelRefillService.sumFuelAmountByVehicleId(vehicleId);
            return Result.success(amount);
        } catch (Exception e) {
            log.error("获取车辆加油总量失败", e);
            return Result.error("获取车辆加油总量失败：" + e.getMessage());
        }
    }

    /**
     * 获取车辆加油总费用
     */
    @GetMapping("/cost/{vehicleId}")
    public Result<BigDecimal> getFuelCost(@PathVariable Long vehicleId) {
        log.info("获取车辆加油总费用: vehicleId={}", vehicleId);
        
        try {
            BigDecimal cost = fuelRefillService.sumTotalPriceByVehicleId(vehicleId);
            return Result.success(cost);
        } catch (Exception e) {
            log.error("获取车辆加油总费用失败", e);
            return Result.error("获取车辆加油总费用失败：" + e.getMessage());
        }
    }

    /**
     * 获取月度加油统计数据
     */
    @GetMapping("/statistics")
    public Result<List<Map<String, Object>>> getStatistics(
            @RequestParam(value = "year", required = false) Integer year) {
        log.info("获取月度加油统计数据: year={}", year);
        
        try {
            List<Map<String, Object>> statistics = fuelRefillService.statisticsByMonth(year);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取月度加油统计数据失败", e);
            return Result.error("获取月度加油统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 测试接口是否正常
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("加油记录API正常运行");
    }
} 